#ifndef __EE_GAMEASSETMANAGER_HPP
#define __EE_GAMEASSETMANAGER_HPP

#include <map>
#include <string>

namespace EE
{
	template< class T >
	class AssetManager
	{
		public:
			AssetManager()
			{
			}

			virtual ~AssetManager()
			{
				ReleaseAllresourceMap();
			}

			typedef std::pair< std::string, T* > Resource;
			typedef std::map< std::string, T* > ResourceMap;
			typedef std::map< std::string, unsigned int > ResourceAllocs;

			T &Load(const std::string& id)
			{
				T* resource = FindResource(id);
				if (resource == NULL)
				{
					resource = LoadFromDisk(id);
					if (resource != NULL)
					{
						resourceMap[id] = resource;
						//resourceMap.insert(Resource(id, resource));
					}
				}
				allocMap[id]++;
				return *resource;
			}

			void Unload(const std::string &id)
			{
				allocMap[id]--;
				if (allocMap[id] == 0)
				{
					ReleaseResource(id);
				}
			}

			void ReleaseResource(const std::string& id)
			{
				T* resource = FindResource(id);
				if (resource != NULL)
				{
					delete resource;
					resourceMap.erase(resourceMap.find(id));
				}
			}

			void ReleaseAllresourceMap()
			{
				while (resourceMap.begin() != resourceMap.end())
				{
					delete resourceMap.begin()->second;
					resourceMap.erase(resourceMap.begin());
				}
			}

		protected:
			virtual T* LoadFromDisk(const std::string &id)=0;

		private:
			ResourceMap resourceMap;
			ResourceAllocs allocMap;

			T* FindResource(const std::string& id)
			{
				T* resource = NULL;
				typename ResourceMap::iterator it = resourceMap.find(id);
				if (it != resourceMap.end())
				{
					resource = (*it).second;
				}

				return resource;
			}
	};
}

#endif
